package com.youlemall.shop.controller;

import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 图片上传控制器
 * 2 * @Author: kevin
 * 3 * @Date: 2019/7/20 9:28
 * 4
 */
@RestController
public class UploadController {


	@Value("${fileUrl}")
	private String fileUrl;

	@PostMapping("/upload")
	public Map<String,Object> uploadFile(@RequestParam("file")MultipartFile multipartFile){
		Map<String,Object> data = new HashMap<>();
		try {
			String path = this.getClass().getResource("/fastdfs_client.conf").getPath();
			ClientGlobal.init(path);
			StorageClient storageClient =new StorageClient();
			String originalFilename = multipartFile.getOriginalFilename();
			//上传文件到fastdfs 服务器
			String[] arr = storageClient.upload_file(multipartFile.getBytes(),
					FilenameUtils.getExtension(originalFilename), null);
			StringBuilder url = new StringBuilder(fileUrl);
			for (String s : arr) {
				url.append("/"+s);
			}
			data.put("url",url.toString());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}
}
